<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Token Login</title>
    </head>
    <body>
        <div id="app">
            <div>
                <input v-model="username" />
                <input v-model="password" />
            </div>

            <div>
                <button v-on:click="login">Login</button>
                <button v-on:click="logout">Logout</button>
                <button v-on:click="getUser">GetUser</button>
            </div>

            <div>
                <button @click="logs=[]">Clear Log</button>
            </div>

            <!-- 日志 -->
            <ul>
                <li v-for="(log, index) in logs" :key="index">{{ log }}</li>
            </ul>
        </div>
    </body>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        axios.interceptors.request.use(
            (config) => {
                const token = window.sessionStorage.getItem('token');
                if (token) {
                    // 判断是否存在 token，如果存在的话，则每个 http header 都加上 token
                    // Bearer 是 JWT 的认证头部信息
                    config.headers.common['Authorization'] = 'Bearer ' + token;
                }
                return config;
            },
            (err) => {
                return Promise.reject(err);
            }
        );

        axios.interceptors.response.use(
            (response) => {
                const res = response.data;
                app.logs.push(JSON.stringify(res));
                return res;
            },
            (err) => {
                app.logs.push(JSON.stringify(response.data));
                return Promise.reject(err);
            }
        );

        var app = new Vue({
            el: '#app',
            data: {
                username: 'test',
                password: 'test',
                logs: [],
            },
            methods: {
                async login() {
                    const res = await axios.post('/login', {
                        username: this.username,
                        password: this.password,
                    });
                    window.sessionStorage.setItem('token', res.data.token);
                },
                async logout() {
                    window.sessionStorage.removeItem('token');
                },
                async getUser() {
                    await axios.get('/users/current');
                },
            },
        });
    </script>
</html>
